package com.fantasy.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @author fantasy
 */
public class HttpClientUtil {
	
	private static HttpClient httpclient = HttpClients.createDefault();
	private static UrlEncodedFormEntity paramEntity = null;
	private static HttpPost httppost = null;
	private static HttpGet httpGet = null;
	private static String cookie = null;
	
	public static void main(String[] args) {
		
	}
	
	/**
	 * 提交的参数
	 * @throws UnsupportedEncodingException 
	 * */
	public static void addParams(HashMap<String , String> params) throws UnsupportedEncodingException{
		 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		 for (Entry<String, String> param : params.entrySet()) {
			formparams.add(new BasicNameValuePair(param.getKey(), param.getValue()));
		}
		paramEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
	}
	
	public static void setPostHeader(HashMap<String , String> header){
		for (Entry<String, String> param : header.entrySet()) {
			httppost.setHeader(param.getKey(), param.getValue());
		}
	}
	
	public static void newHttpPost(String url){
		httppost = new HttpPost(url);
	}
	
	public static void newHttpGet(String url){
		httpclient = HttpClients.createDefault();
		httpGet = new HttpGet(url);
	}
	
	public static void setCookie(HttpResponse response){
		String cookieTemp = response.getFirstHeader("Set-Cookie").getValue();
		if("".equals(cookieTemp) || cookieTemp != null){
			cookie = cookieTemp;
		}
	}
	
	public static void setCookie(String cookieValue){
		cookie = cookieValue;
	}
	
	public static String executePostSetCookie() throws ClientProtocolException, IOException{
		return executePost(true);
	}
	public static String executePost() throws ClientProtocolException, IOException{
		return executePost(false);
	}
	
	public static String executePost(boolean setCookieStat) throws ClientProtocolException, IOException{
		httppost.setHeader("Cookie", cookie);
		postSetEntity();
		HttpResponse response = httpclient.execute(httppost);
		if(setCookieStat){
			setCookie(response);
		}
		// 打印返回的结果
		HttpEntity entity = response.getEntity();
		
		StringBuilder result = new StringBuilder();
		if (entity != null) {
			InputStream instream = entity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(instream));
			String temp = "";
			while ((temp = br.readLine()) != null) {
				String str = new String(temp.getBytes(), "utf-8");
				result.append(str);
			}
		}
		return result.toString();
	}
	
	public static void postSetEntity(){
		httppost.setEntity(paramEntity);
	}
	
	public static String executeGet(String charset ) throws ParseException, IOException {
		//httpGet.setHeader("Cookie", cookie);
		HttpResponse response = httpclient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		//System.out.println(response.getStatusLine().getStatusCode());
		if(response.getStatusLine().getStatusCode() == 404){
			System.out.println("  页面不存在404");
			return "";
		}
		String respContent = EntityUtils.toString(entity , charset).trim();
		return respContent;
	}
	
	public static String executeGet() throws ParseException, IOException  {
		return executeGet("utf-8");
	}
}